package com.ushine.web.template.transactional.facade.impl;

import com.ushine.web.component.exception.ServiceException;
import com.ushine.web.template.transactional.facade.ISecondTransactionFacade;
import com.ushine.web.template.transactional.facade.ITransactionFacade;
import com.ushine.web.template.transactional.model.FirstTransactionDO;
import com.ushine.web.template.transactional.model.SecondTransactionDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @Author: yls
 * @Date: 2022/02/21 09:14
 * @Description: 模拟包装层嵌套包装层实现复杂的事务控制测试
 * @Version 1.0
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class SecondTransactionFacadeImpl implements ISecondTransactionFacade {

    @Resource
    private ITransactionFacade transactionFacade;

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void insetFirstAndSecond(FirstTransactionDO firstTransaction, FirstTransactionDO firstTransaction02,
                                    SecondTransactionDO secondTransaction, SecondTransactionDO secondTransaction02) {
        log.info("进入正常嵌套事务。");
        transactionFacade.insetFirstAndSecond(firstTransaction, secondTransaction);
        transactionFacade.insetFirstAndSecond(firstTransaction02, secondTransaction02);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void insetFirstAndSecondException(FirstTransactionDO firstTransaction, FirstTransactionDO firstTransaction02,
                                             SecondTransactionDO secondTransaction, SecondTransactionDO secondTransaction02) throws ServiceException {
        log.info("进入回滚嵌套事务。");
        transactionFacade.insetFirstAndSecond(firstTransaction, secondTransaction);
        transactionFacade.insetFirstAndSecondException(firstTransaction02, secondTransaction02);
    }

    @Override
    @Transactional(propagation = Propagation.NESTED, rollbackFor = Exception.class)
    public void insetNestedException(FirstTransactionDO firstTransaction,
                                     FirstTransactionDO firstTransaction02,
                                     SecondTransactionDO secondTransaction,
                                     SecondTransactionDO secondTransaction02) throws ServiceException {
        log.info("进入回滚嵌套事务。");
        transactionFacade.insetFirstAndSecond(firstTransaction, secondTransaction);
        transactionFacade.insetNestedException(firstTransaction02, secondTransaction02);
    }
}
